package org.zoomdev.zoom.asm;

import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;

import java.util.ArrayList;
import java.util.List;

public class ClassBuilder {
    private final String className;
    private String superName = Type.getInternalName(Object.class);
    private final List<String> interfaces = new ArrayList<>();
    private final List<FieldBuilder> fields = new ArrayList<>();
    private final List<MethodBuilder> methods = new ArrayList<>();

    public ClassBuilder(String className) {
        this.className = className.replace('.', '/');
    }

    public ClassBuilder extend(Class superName) {
        this.superName = Type.getInternalName(superName);
        return this;
    }

    public ClassBuilder implement(Class interfaceName) {
        this.interfaces.add(Type.getInternalName(interfaceName));
        return this;
    }

    public ClassBuilder addField(FieldBuilder field) {
        fields.add(field);
        return this;
    }

    public ClassBuilder addMethod(MethodBuilder method) {
        methods.add(method);
        return this;
    }

    public byte[] build() {
        ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);

        // 类定义
        cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC | Opcodes.ACC_SUPER,
                className, null, superName,
                interfaces.toArray(new String[0]));

        // 添加字段
        for (FieldBuilder field : fields) {
            field.build(cw);
        }

        // 添加方法
        for (MethodBuilder method : methods) {
            method.build(cw, className);
        }

        cw.visitEnd();
        return cw.toByteArray();
    }
}
